import { defer } from "@/utils/defer";
import deepcopy from "deepcopy";
import { ElButton, ElDialog, ElInput, ElTable, ElTableColumn } from "element-plus";
import { createApp, defineComponent, getCurrentInstance, onMounted, reactive } from "vue";

const [Dialog, Table, Button, TableColumn, Input] = [ElDialog, ElTable, ElButton, ElTableColumn, ElInput];

const ServiceComponent = defineComponent({
  name: "service-component",
  props: {
    option: {
      type: Object,
      required: true,
    },
  },

  setup(props) {
    const current = getCurrentInstance();
    const state = reactive({
      option: props.option,
      showFlag: false,
      mounted: (() => {
        // 在显示弹层时调用  vue组件， 加载事件
        const dfd = defer();
        onMounted(dfd.resolve); // 加载数据
        return dfd.promise;
      })(),
      editorData: [], // 弹层的编辑数据
    });

    const methods = {
      // 打开弹层调用方法
      open: (option) => {
        state.option = option; // 将参数暂存
        state.editorData = deepcopy(option.data || []);
        methods.show();
      },
      show: async () => {
        await state.mounted;
        state.showFlag = true;
      },
      hide: () => {
        state.showFlag = false;
      },
      add: () => {
        state.editorData.push({}); // 添加一条空记录
      },
      reset: () => {
        // 重置 回到初始数据状态 option.data
        state.editorData = deepcopy(state.option.data || []);
      },
    };
    // 将methods赋值给current组件的实例对象
    Object.assign(current.proxy, methods);

    // 事件处理
    const handler = {
      onConfirm: () => {
        // 确定  1. 将数据回传  2.hide
        state.option.onConfirm(state.editorData); // 将数据回传
        methods.hide();
      },
      onCancel: () => {
        // 取消  就是hide
        methods.hide();
      },
      onDelete: (index) => {
        // 使用数组的splice删除方法
        state.editorData.splice(index, 1);
      },
    };

    return () => (
      <Dialog v-model={state.showFlag}>
        {{
          default: () => (
            <div>
              <div>
                <Button onClick={methods.add}>添加</Button>
                <Button onClick={methods.reset}>重置</Button>
              </div>
              <Table data={state.editorData}>
                <TableColumn type="index" />
                {state.option.config.table?.options.map((item, index) => (
                  <TableColumn label={item.label}>
                    {{
                      default: ({ row }) => <Input v-model={row[item.field]} />,
                    }}
                  </TableColumn>
                ))}
                <TableColumn label="操作">
                  {{
                    default: ({ $index }) => (
                      <Button type="danger" onClick={() => handler.onDelete($index)}>
                        删除
                      </Button>
                    ),
                  }}
                </TableColumn>
              </Table>
            </div>
          ),
          footer: () => (
            <>
              <Button onClick={handler.onCancel}>取消</Button>
              <Button onClick={handler.onConfirm} type="primary">
                确定
              </Button>
            </>
          ),
        }}
      </Dialog>
    );
  },
});

export const $tablePropEditor = (() => {
  let ins;
  return (option) => {
    console.log("🚀 ~ option:", option);
    if (!ins) {
      // 弹层没有实例化
      const el = document.createElement("div");
      document.body.appendChild(el);
      const app = createApp(ServiceComponent, { option });
      ins = app.mount(el);
    }
    const dfd = defer();
    ins.open({
      ...option,
      onConfirm: dfd.resolve, // 点击确定后的处理
    });
    return dfd.promise;
  };
})();
